package com.walala.logic.handler;

import com.google.protobuf.InvalidProtocolBufferException;
import com.walala.logic.annotation.HandlerContract;
import com.walala.logic.common.Command;
import com.walala.logic.pojo.ChatMsgBean;
import com.walala.logic.pojo.msg.MsgProtoc;
import com.walala.logic.protocol.IMProto.ChatMsg;
import com.walala.logic.protocol.ProtocolPackage;
import com.walala.logic.service.ChatMsgService;
import com.walala.logic.threads.BlockThreadPool;
import com.walala.logic.utils.ProtoMessageUtil;
import com.walala.logic.worker.SendMsgWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author KayLi
 */
@HandlerContract(cmd = Command.IMMSG)
public class ChatMsgHandler implements MsgHandler{

    private Logger logger = LoggerFactory.getLogger(ChatMsgHandler.class);

    private static BlockThreadPool threadPool;
    static{
        threadPool = new BlockThreadPool(10,20,"forward-msg-thread");
        threadPool.openMonitor(10,false);
    }

    @Override
    public void process(ProtocolPackage pack) {

        try {
            byte[] protoBody = pack.getProtoBody();
            ChatMsg chatMsg = ChatMsg.parseFrom(protoBody);
            ChatMsgBean msgBean = ProtoMessageUtil.pbToChatMsgBean(chatMsg);

            String sessionId = chatMsg.getSessionId();

            if(ChatMsgService.saveMsg(msgBean)){
                SendMsgWorker worker = new SendMsgWorker(pack,msgBean);
                threadPool.addTask(worker);
            }
        } catch (Exception e) {
            logger.error("chatMsgHandler process error,cmd:{},senderId:{},receiverid:{},traceId:{}",pack.getCommand(),
                    pack.getCommand(),pack.getSenderId(), pack.getReceiverId(),pack.getTraceId(),e);
        }
    }

    @Override
    public void process(MsgProtoc msg) {
    }
}
